package com.springdoor.goods.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.springdoor.common.core.domain.entity.SprdGoodsAttr;
import com.springdoor.common.core.domain.entity.SprdGoodsAttrVal;
import com.springdoor.common.core.domain.entity.SprdGoodsBrand;
import com.springdoor.common.core.domain.entity.SprdGoodsType;
import com.springdoor.goods.domain.SprdCommonImages;
import com.springdoor.goods.domain.SprdGoodsConfig;
import com.springdoor.goods.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.springdoor.goods.domain.SprdGoodsMain;
import com.springdoor.goods.service.ISprdGoodsMainService;

/**
 * 商品主体信息Service业务层处理
 *
 * @author llshs
 * @date 2024-05-21
 */
@Service
public class SprdGoodsMainServiceImpl implements ISprdGoodsMainService
{
    @Autowired
    private SprdGoodsMainMapper mainMapper;

    @Autowired
    private SprdGoodsConfigMapper configMapper;

    @Autowired
    private SprdGoodsImgMapper imgMapper;

    @Autowired
    private SprdGoodsDescMapper descMapper;

    @Autowired
    private SprdCommonImagesMapper commonImagesMapper;

    @Autowired
    private SprdGoodsBrandMapper brandMapper;

    @Autowired
    private SprdGoodsAttrMapper attrMapper;

    @Autowired
    private SprdGoodsAttrValMapper attrValMapper;

    /**
     * 查询商品主体信息
     *
     * @param goodsId 商品主体信息主键
     * @return 商品主体信息
     */
    @Override
    public SprdGoodsMain selectSprdGoodsMainByGoodsId(Long goodsId)
    {
        return mainMapper.selectSprdGoodsMainByGoodsId(goodsId);
    }

    @Override
    public SprdGoodsMain selectSprdGoodsMainByGNumber(String goodsCode) {
        return mainMapper.selectSprdGoodsMainByGNumber(goodsCode);
    }

    /**
     * 查询商品主体信息列表
     *
     * @param sprdGoodsMain 商品主体信息
     * @return 商品主体信息
     */
    @Override
    public List<SprdGoodsMain> selectSprdGoodsMainList(SprdGoodsMain sprdGoodsMain)
    {
        return mainMapper.selectSprdGoodsMainList(sprdGoodsMain);
    }

    /**
     * 新增商品主体信息
     *
     * @param main 商品主体信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSprdGoodsMain(SprdGoodsMain main)
    {
        String gNumber = generateGNumber(main);
        main.setgNumber(gNumber);
        if (main.getImageId() == null || main.getImageId() <= 0) {
            Long imageId = insertGoodsMainImage(main);
            main.setImageId(imageId);
        }
        return mainMapper.insertSprdGoodsMain(main);
    }

    private Long insertGoodsMainImage(SprdGoodsMain main) {
        SprdCommonImages commonImages = new SprdCommonImages();
        commonImages.setCreateBy(main.getUpdateBy());
        commonImages.setUpdateBy(main.getUpdateBy());
        commonImages.setgNumber(main.getgNumber());
        commonImages.setgName(main.getGoodsName());
        commonImages.setImageName(main.getGoodsName());
        commonImages.setImageType("1");//封面
        commonImages.setImageServer("qiniu");
        commonImages.setImagePath(main.getImage());
        commonImages.setOrderNum(1);
        commonImagesMapper.insertSprdCommonImages(commonImages);
        return commonImages.getImageId();
    }

    /**
     * 生成 商品编码
     * @param main
     * @return
     */
    private String generateGNumber(SprdGoodsMain main) {
        String code = null;
        try {
            SprdGoodsBrand brand = brandMapper.selectSprdGoodsBrandByBrandId(main.getBrandId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String s = brand.getBrandCode() + sdf.format(new Date()) + Math.abs(UUID.randomUUID().getMostSignificantBits());
            code = s.substring(0, 24);
        } catch (Exception e) {
            throw new RuntimeException("生成商品编码号错误");
        }
        return code;
    }

    /**
     * 修改商品主体信息
     *
     * @param sprdGoodsMain 商品主体信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSprdGoodsMain(SprdGoodsMain sprdGoodsMain)
    {
        SprdGoodsMain main = mainMapper.selectSprdGoodsMainByGoodsId(sprdGoodsMain.getGoodsId());
        if (sprdGoodsMain.getImageId() == null || sprdGoodsMain.getImageId() <= 0) {
            Long imageId = insertGoodsMainImage(sprdGoodsMain);
            sprdGoodsMain.setImageId(imageId);
        }
        return mainMapper.updateSprdGoodsMain(sprdGoodsMain);
    }

    /**
     * 删除商品主体信息信息
     *
     * @param gNumber 商品主体编码
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteGoodsByGnumber(String gNumber)
    {
        List<SprdGoodsMain> mains = mainMapper.selectAssGoodsByGnumber(gNumber);
        String [] list = new String[mains.size()];
        for (int i = 0; i < mains.size(); i++) {
            list[i] = mains.get(i).getgNumber();
        }
        configMapper.deleteSprdGoodsConfigByGNumbers(list);
        imgMapper.deleteSprdGoodsImgByGNumbers(list);
        descMapper.deleteSprdGoodsDescByGNumbers(list);
        return mainMapper.deleteSprdGoodsMainByGnumbers(list);
    }

    @Override
    public Integer findMaxOrderNum(String assNumber) {
        if (StringUtils.isEmpty(assNumber) || "0".equals(assNumber)) {
            assNumber = null;
        }
        return mainMapper.findMaxOrderNum(assNumber);
    }

    @Override
    public Map<String, Object> getAssortInfo(String gNumber) {
        SprdGoodsMain main = mainMapper.selectSprdGoodsMainByGNumber(gNumber);
        if (main == null) {
            return null;
        }
        try {
            String assort = main.getAssort();
            if (StringUtils.isEmpty(assort)) {
                return null;
            }
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> list = new ArrayList<>();
            String assNumber = StringUtils.isEmpty(main.getAssNumber()) ? gNumber : main.getAssNumber();
            if (StringUtils.isNotEmpty(assort)) {
                String[] split = assort.split(",");
                List<SprdGoodsConfig> configList = configMapper.selectAssortConfigByGNumber(gNumber, split);
                Map<String, SprdGoodsConfig> configMap = new HashMap<>();
                if (configList != null && !configList.isEmpty()) {
                    for (SprdGoodsConfig config : configList) {
                        configMap.put(config.getAttrId(), config);
                    }
                }
                result.put("assort", configMap);
                List<SprdGoodsConfig> configs = configMapper.selectAssortConfig(assNumber, split);
                Map<String, Object> goodsMap = new HashMap<>();
                for (SprdGoodsConfig config : configs) {
                    Map<String, Object> attrMap = (Map<String, Object>) goodsMap.get(config.getgNumber());
                    if (attrMap == null) {
                        attrMap = new HashMap<>();
                    }
                    attrMap.put(config.getAttrId(), config.getValueId());
                    goodsMap.put(config.getgNumber(), attrMap);
                }
                System.out.println("--------------------------------");
                System.out.println(goodsMap);
                Map<String, Map<String, Object>> attrMap = new HashMap<>();
                for (SprdGoodsConfig config : configs) {
                    Map<String, Object> attrValMap = attrMap.get(config.getAttrId());
                    if (attrValMap == null) {
                        attrValMap = new HashMap<>();
                    }
                    Map<String, Object> goodsMains = (Map<String, Object>) attrValMap.get(config.getValueId());
                    if (goodsMains == null) {
                        goodsMains = new HashMap<>();
                    }
                    Map<String, String> attrs = (Map<String, String>) goodsMains.get(config.getgNumber());
                    if (attrs == null) {
                        attrs = new HashMap<>();
                    }
                    attrs.put(config.getValueId(), config.getValueName());
                    goodsMains.put(config.getgNumber(), goodsMap.get(config.getgNumber()));
                    attrValMap.put(config.getValueId(), goodsMains);
//                    attrValMap.put(config.getValueId(), goodsMap);
                    attrMap.put(config.getAttrId(), attrValMap);
                }
                System.out.println(attrMap);

                for (String attrId : split) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("attrId", attrId);
                    SprdGoodsConfig c = configMap.get(attrId);
                    SprdGoodsAttr attr = attrMapper.selectSprdGoodsAttrByAttrId(Long.parseLong(attrId));
                    if (c == null) {
                        if (attr != null) {
                            map.put("label", attr.getAttrName());
                            SprdGoodsAttrVal av = new SprdGoodsAttrVal();
                            av.setAttrId(Long.parseLong(attrId));
                            List<SprdGoodsAttrVal> attrVals = attrValMapper.selectSprdGoodsAttrValList(av);
                            if (attrVals != null && !attrVals.isEmpty()) {
                                List<Map<String, Object>> options = new ArrayList<>();
                                for (SprdGoodsAttrVal v : attrVals) {
                                    Map<String, Object> option = new HashMap<>();
                                    option.put("value", v.getValueId().toString());
                                    option.put("label", v.getValueLabel());
                                    option.put("goods", attrMap.get(attrId).get(v.getValueId()));
                                    options.add(option);
                                }
                                map.put("options", options);
                            }
                            list.add(map);
                        }
                    } else {
                        map.put("label", c.getAttrName());
                        map.put("value", c.getValueId());
                        List<Map<String, Object>> options = new ArrayList<>();
                        Set<String> set = new HashSet<>();
                        SprdGoodsAttrVal av = new SprdGoodsAttrVal();
                        av.setAttrId(Long.parseLong(attrId));
                        List<SprdGoodsAttrVal> attrVals = attrValMapper.selectSprdGoodsAttrValList(av);
                        if (attrVals != null && !attrVals.isEmpty()) {
                            for (SprdGoodsAttrVal val : attrVals) {
                                set.add(val.getValueId().toString());
                                Map<String, Object> v = new HashMap<>();
                                v.put("value", val.getValueId().toString());
                                v.put("label", val.getValueLabel());
                                v.put("goods", attrMap.get(attrId).get(val.getValueId().toString()));
                                System.out.println(v.get("goods"));
                                options.add(v);
                            }
                        }
                        Map<String, String> param = new HashMap<>();
                        param.put("assNumber", assNumber);
                        param.put("attrId", attrId);
                        List<SprdGoodsConfig> valueList = configMapper.selectAttrValuesByAssNumber(param);
                        if (valueList != null && !valueList.isEmpty()) {
                            for (SprdGoodsConfig config : valueList) {
                                String valueId = config.getValueId();
                                if (StringUtils.isNotEmpty(valueId)) {
                                    if (StringUtils.isNotBlank(config.getConfigVal())) {
                                        Map<String, Object> v = new HashMap<>();
                                        v.put("value", valueId);
                                        v.put("label", config.getConfigVal());
                                        v.put("goods", attrMap.get(attrId).get(valueId));
                                        options.add(v);
                                    } else {
                                        String[] values = valueId.split(",");
                                        String[] names = config.getValueName().split(",");
                                        for (int i=0; i<values.length; i++) {
                                            if (set.add(values[i])) {
                                                Map<String, Object> v = new HashMap<>();
                                                v.put("value", values[i]);
                                                v.put("label", names[i]);
                                                v.put("goods", attrMap.get(attrId).get(values[i]));
                                                options.add(v);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (options.size() > 0) {
                            map.put("options", options);
                        }
                        list.add(map);
                    }
                }
                result.put("assortOptions", list);
                return  result;
            }
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    @Override
    public List<SprdGoodsMain> selectGoodsMainListNotinShop(SprdGoodsMain sprdGoodsMain) {
        return mainMapper.selectGoodsMainListNotinShop(sprdGoodsMain);
    }
}
